package com.burningtower.controller;

import com.burningtower.common.Pages;
import com.burningtower.common.Result;
import com.burningtower.entity.Order;
import com.burningtower.enums.AliCallbackEnum;
import com.burningtower.enums.OrderStatusEnum;
import com.burningtower.service.OrderItemService;
import com.burningtower.service.OrderService;
import com.burningtower.vo.OrderCartProductVo;
import com.burningtower.vo.OrderItemVo;
import com.burningtower.vo.OrderVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("order")
public class OrderController {
    private static final Logger logger=LoggerFactory.getLogger(OrderController.class);

    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderItemService orderItemService;

    /**
     * 创建订单
     * @param shippingId
     * @param session
     * @return Result<OrderVo>
     */
    @GetMapping("create.do")
    public Result<OrderVo> create(Integer shippingId,
                                  HttpSession session){
        //取出当前userId
        Integer userId = (Integer) session.getAttribute("userId");
        if(userId==null){
            throw new RuntimeException("NEED_LOGIN");
        }
        OrderVo vo=null;
        try {
            Order order = orderService.add(userId, shippingId);//新增order，以及相关OrderItem
            vo = orderService.toVo1(order);
        }catch (Exception e){
            throw new RuntimeException("创建订单失败");
        }

        Result<OrderVo> result=new Result<>();//返回result
        result.setData(vo);
        result.setStatus(0);
        return result;
    }

    /**
     * 返回购物车包含的所有OrderItemVo（无用）
     * @param session
     * @return Result<OrderCartProductVo>
     */
    @GetMapping("get_order_cart_product.do")
    public Result<OrderCartProductVo> getOrderCartProduct(HttpSession session){
        //取出当前userId
        Integer userId = (Integer) session.getAttribute("userId");
        if(userId==null){
            throw new RuntimeException("NEED_LOGIN");
        }

        //获取购物车的商品
        List<OrderItemVo> itemVoList = orderItemService.getVoListByUserId(userId);

        //获得总价
        BigDecimal price=new BigDecimal(0);
        for(OrderItemVo itemVo:itemVoList){
            price=price.add(itemVo.getTotalPrice());
        }

        Result<OrderCartProductVo> result=new Result<>();//新建返回result
        OrderCartProductVo vo=new OrderCartProductVo();//新建result中的vo
        vo.setProductTotalPrice(price);
        vo.setImageHost("http://img.happymmall.com/");
        vo.setOrderItemVoList(itemVoList);
        result.setData(vo);
        result.setStatus(0);
        return result;
    }

    /**
     * 获得当前用户所有订单以分页传回
     * @param session
     * @return Pages<OrderVo>
     */
    @GetMapping("list.do")
    public Result<Pages<OrderVo>> list(HttpSession session,
                                       @RequestParam(required = false,defaultValue = "10") Integer pageSize,
                                       @RequestParam(required = false,defaultValue = "1") Integer pageNum){
        //取出当前userId
        Integer userId = (Integer) session.getAttribute("userId");
        if(userId==null){
            throw new RuntimeException("NEED_LOGIN");
        }
        //获取分页结果
        Pages<OrderVo> pageVo = orderService.getPagesByUserId(userId, pageNum, pageSize, "createTime_desc");

        Result<Pages<OrderVo>> result=new Result<>();
        result.setData(pageVo);
        result.setStatus(0);
        return result;
    }

    /**
     * 返回订单详情
     * @param session
     * @param orderNo
     * @return
     */
    @RequestMapping("detail.do")
    public Result<OrderVo> detail(HttpSession session,
                                  Long orderNo){
        //取出当前userId
        Integer userId = (Integer) session.getAttribute("userId");
        if(userId==null){
            throw new RuntimeException("NEED_LOGIN");
        }
        //获取order
        Order order = orderService.getOrderByUserIdAndOrderNo(userId, orderNo);
        if(order==null){
            throw new RuntimeException("没有找到订单");
        }
        //将order赋给vo
        OrderVo orderVo = orderService.toVo(order);
        Result<OrderVo> result=new Result<>();
        result.setStatus(0);
        result.setData(orderVo);
        return result;
    }

    /**
     * 取消订单
     * @param orderNo
     * @param session
     * @return
     */
    @RequestMapping("cancel.do")
    public Result cancel(Long orderNo,HttpSession session){
        //取出当前userId
        Integer userId = (Integer) session.getAttribute("userId");
        if(userId==null){
            throw new RuntimeException("NEED_LOGIN");
        }
        orderService.cancel(userId,orderNo);
        Result result=new Result();
        result.setStatus(0);
        return result;
    }

    //-------------------以下是支付---------------------

    /**
     * 支付
     * @param session
     * @param request
     * @param orderNo
     * @return
     */
    @RequestMapping("pay.do")
    public Result<Map<String,String>> pay(HttpSession session, HttpServletRequest request,
                           @RequestParam Long orderNo){
        Integer userId = (Integer) session.getAttribute("userId");
        if(userId==null){
            throw new RuntimeException("NEED_LOGIN");
        }
//        设置图片缓存路径，暂时硬保存在本地，路径见orderServiceImpl.pay
//        String path = request.getSession().getServletContext().getRealPath("upload");

        return orderService.pay(orderNo,userId,null);
    }

    /**
     * 回调验证
     * @param request
     * @return
     */
    @RequestMapping("alipay_callback.do")
    public Object alipayCallback(HttpServletRequest request){
        Map<String,String> params=new HashMap<>();
        Map<String, String[]> parameterMap = request.getParameterMap();
        for(Iterator iterator=parameterMap.keySet().iterator();iterator.hasNext();){
            String name = (String) iterator.next();
            String[] strings = parameterMap.get(name);
            String value="";
            for(int i=0;i<strings.length;i++){
                value=value+strings[i]+(i==(strings.length-1)?"":",");
            }
            params.put(name,value);
        }
        logger.info("支付宝回调：sign{},trade_status{},参数{}",params.get("sign"),params.get("trade_status"),params.toString());
//        验证回调的正确性
        params.remove("sign_type");
        /*try {
            boolean checkV2 = AlipaySignature.rsaCheckV2(params, Configs.getAlipayPublicKey(), "utf-8", Configs.getSignType());
            if(!checkV2){
                throw new RuntimeException("非法请求");
            }

        } catch (AlipayApiException e) {
            logger.error("支付宝回调异常",e);
        }
*/
        //验证其他数据，包括订单号、订单状态
        if(orderService.aliCallback(params)){
            return AliCallbackEnum.RESPONSE_SUCCESS;
        }
        return AliCallbackEnum.RESPONSE_FAILED;
    }

    /**
     * 检查订单状态是否完成了支付，如是则返回true
     * @param session
     * @param orderNo
     * @param request
     * @return
     */
    @RequestMapping("query_order_pay_status.do")
    public Result<Boolean> queryOrderPayStatus(HttpSession session,
                                               Long orderNo,
                                               HttpServletRequest request){
        Result<Boolean> result=new Result<>();
        Integer userId = (Integer) session.getAttribute("userId");
        if(userId==null){
            throw new RuntimeException("NEED_LOGIN");
        }
        Order order = orderService.getOrderByUserIdAndOrderNo(userId,orderNo);
        if(order==null){
            throw new RuntimeException("用户没有该订单");
        }
        boolean b = order.getStatus() >= OrderStatusEnum.PAID.getCode();
        result.setData(b);
        result.setStatus(0);
        return result;
    }
}
